import { QuestionCircleOutlined } from '@ant-design/icons';
import {
  type ActionType,
  PageContainer,
  type ProColumns,
  ProDescriptions,
  type ProDescriptionsItemProps,
  ProTable,
} from '@ant-design/pro-components';
import { useIntl, useRequest } from '@umijs/max';
import {
  Button,
  Drawer,
  Dropdown,
  Flex,
  message,
  Popconfirm,
  Space,
} from 'antd';
import React, { useCallback, useRef, useState } from 'react';
import { fetchCarSend } from '@/apis/order';
import { ColumnMap } from '@/pages/order/Order.data';
import type { BusinessOrderVO } from '@/pages/order/schema';
import { removeRule, rule } from '@/services/ant-design-pro/api';
import CreateForm, {
  type CreateFormRef,
} from './components/CreateForm/CreateForm';

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType | null>(null);

  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();
  const [selectedRowsState, setSelectedRows] = useState<any>([]);

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const [messageApi, contextHolder] = message.useMessage();

  const { run: delRun, loading } = useRequest(removeRule, {
    manual: true,
    onSuccess: () => {
      setSelectedRows([]);
      actionRef.current?.reloadAndRest?.();

      messageApi.success('删除成功');
    },
    onError: () => {
      messageApi.error('删除失败，请重试');
    },
  });

  const columns: ProColumns<BusinessOrderVO>[] = [];

  const columnMap: { [key: string]: ProColumns<BusinessOrderVO> } =
    Object.assign(
      {
        operation: {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          width: 160,
          align: 'center',
          search: false,
          render: (text: any, record: any) => (
            <Flex gap={8} justify={'center'}>
              <Button
                size="small"
                color="primary"
                variant="outlined"
                onClick={() => handleEdit(record)}
              >
                编辑
              </Button>
              <Popconfirm
                title="提示"
                description="是否删除当前记录?"
                icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
                onConfirm={() => {
                  handleDelete(record);
                }}
              >
                <Button size={'small'} color="default" variant="outlined">
                  删除
                </Button>
              </Popconfirm>
            </Flex>
          ),
        },
      },
      ColumnMap,
    );
  for (const key in columnMap) {
    const column = columnMap[key as keyof typeof columnMap];
    column.key = key;
    columns.push(column);
  }

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = useCallback(
    async (selectedRows: API.RuleListItem[]) => {
      if (!selectedRows?.length) {
        messageApi.warning('请选择删除项');

        return;
      }
    },
    [delRun, messageApi.warning],
  );

  const handleDelete = useCallback(async (record: any) => {
    const res = await delRun(record.id);
  }, []);

  const createRef = useRef<CreateFormRef>(null);
  const handleEdit = (record: BusinessOrderVO) => {
    if (createRef.current) {
      createRef.current.handleEdit(record.id);
    }
  };
  const handleSendCar = useCallback(async (e: any, props: any) => {
    let status = true;
    if (e.key === '1') {
      status = false;
    }
    const res = await fetchCarSend(props.selectedRowKeys.join(','), status);
    if (res.code === 200) {
      message.success(res.data);
      actionRef.current?.reload();
    }
  }, []);

  return (
    <PageContainer>
      {contextHolder}
      <ProTable<BusinessOrderVO, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.title',
          defaultMessage: 'Enquiry form',
        })}
        tableAlertRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => {
          console.log(selectedRowKeys, selectedRows);
          return (
            <Space size={24}>
              <span>
                已选 {selectedRowKeys.length} 项
                <Button
                  type="link"
                  style={{ marginInlineStart: 8 }}
                  onClick={onCleanSelected}
                >
                  取消选择
                </Button>
              </span>
            </Space>
          );
        }}
        tableAlertOptionRender={(props) => {
          return (
            <Space size={16}>
              <Popconfirm
                title="确认删除当前选项？"
                icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
              >
                <Button danger>批量删除</Button>
              </Popconfirm>
              <Dropdown.Button
                type="primary"
                onClick={(e) => handleSendCar(e, props)}
                menu={{
                  items: [{ key: 1, label: '取消派车' }],
                  onClick: (e) => handleSendCar(e, props),
                }}
              >
                派车
              </Dropdown.Button>
            </Space>
          );
        }}
        tableLayout={'auto'}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <CreateForm
            key="create"
            ref={createRef}
            reload={actionRef.current?.reload}
          />,
        ]}
        request={rule}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
        scroll={{ x: 2800, y: 400 }}
      />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
